<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UserAddressRequest;
use App\Model\UserAddress;
use App\Transformers\UserAddressTransformer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserAddressController extends Controller
{
    public function index(Request $request)
    {
        $page = $request->page;
        $order = $request->input('order','desc');
        $addresses = UserAddress::orderBy('id',$order)->paginate($page);
        return $this->response->paginator($addresses,new UserAddressTransformer());
    }

    public function store(UserAddressRequest $request)
    {
        $data = $request->only([
            'province',
            'city',
            'district',
            'address',
            'zip',
            'contact_name',
            'contact_phone',
        ]);

        $res = auth('api')->user()->addresses()->create($data);
        return $this->response->array(responseJson(200,$res,'success'))->setStatusCode(201);
    }

    public function show($address)
    {
        $userAddress = auth('api')->user()->addresses()->where('id',$address)->first();

        // todo 策略 看看是不是自己下面的地址，否则看不见
        $this->authorize('own',$userAddress);

        return $this->response->item($userAddress,new UserAddressTransformer());
    }

    public function update(Request $request, $address)
    {
        $data = $request->only([
            'province',
            'city',
            'district',
            'address',
            'zip',
            'contact_name',
            'contact_phone',
        ]);
        $res = auth('api')->user()->addresses()->where('id',$address)->update($data);
        return $this->response->array(responseJson(200,$res,'success'))->setStatusCode(201);
    }

    public function destroy(UserAddressRequest $request,$address)
    {
        $res = auth('api')->user()->addresses()->where('id',$address)->delete();
        return $this->response->array(responseJson(200,$res,'success'))->setStatusCode(204);

    }
}
